package com.laowang.project.system.service.impl;

import java.beans.Transient;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.DateUtils;
import com.laowang.common.utils.Sample;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.common.utils.aip.BusinessLicense;
import com.laowang.common.utils.aip.CarInfo;
import com.laowang.common.utils.aip.IdCard;
import com.laowang.common.utils.aip.PersonInfo;
import com.laowang.framework.redis.RedisCache;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.laowang.project.system.mapper.MyCarBookMapper;
import org.springframework.transaction.annotation.Transactional;
import oshi.jna.platform.mac.SystemB;

/**
 * 车友通讯录Service业务层处理
 *
 * @author laowang
 * @date 2023-04-20
 */
@Slf4j
@Service
public class MyCarBookServiceImpl implements MyCarBookService {
    @Autowired
    private MyCarBookMapper myCarBookMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private MyCyhCarService myCyhCarService;

    @Autowired
    private MyCyhMarkService myCyhMarkService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    @Autowired
    private MyCarCouponService myCarCouponService;

    /**
     * 查询车友通讯录
     *
     * @param id 车友通讯录ID
     * @return 车友通讯录
     */
    @Override
    public MyCarBook selectMyCarBookById(Integer id) {
        return myCarBookMapper.selectMyCarBookById(id);
    }

    /**
     * 查询车友通讯录列表
     *
     * @param myCarBook 车友通讯录
     * @return 车友通讯录
     */
    @Override
    public List<MyCarBook> selectMyCarBookList(MyCarBook myCarBook) {
        return myCarBookMapper.selectMyCarBookList(myCarBook);
    }

    /**
     * 新增车友通讯录
     *
     * @param myCarBook 车友通讯录
     * @return 结果
     */
    @Override
    public int insertMyCarBook(MyCarBook myCarBook) {
        String autoCheck = myCarBook.getAutoCheck();
        if (StringUtils.isNotEmpty(autoCheck) && autoCheck.equals("1")){

        }else {
            myCarBook.setAutoCheck("0");
        }
        Integer userId = myCarBook.getUserId();
        String car = myCarBook.getCar();
        MyCarBook myCarBook1 = myCarBookMapper.selectMyCarBookByUserId(userId);
        if (myCarBook1 != null) {
            throw new CustomException("认证信息已存在", 400);
        }
        String subCard1 = myCarBook.getSubCard();
        StringBuilder subCard = new StringBuilder(subCard1);
        while (subCard.length() < 4) {
            subCard.insert(0, "0");
        }
        String string = subCard.toString();
        MyCyhMark myCyhMark = new MyCyhMark();
        myCyhMark.setNumber(string);
        myCyhMark.setCarId(car);
        List<MyCyhMark> myCyhMarks = myCyhMarkService.selectMyCyhMarkList(myCyhMark);
        if (myCyhMarks.size()>0 ) {
            throw new CustomException(car+" " +"副牌号:" + subCard1 + "已被占用", 400);
        }
        myCyhMark.setUserId(userId);
        myCarBook.setSubCard(string);
        myCyhMark.setNatime(new Date());
        myCarBookMapper.insertMyCarBook(myCarBook);
        myCyhMarkService.insertMyCyhMark(myCyhMark);

        MyCyhCar myCyhCar = new MyCyhCar();
        myCyhCar.setUserId(userId);
        myCyhCar.setProduct(myCarBook.getCarType());
        myCyhCar.setCtime(new Date( ));
        myCyhCarService.insertMyCyhCar(myCyhCar);
        return 1;
    }

    /**
     * 修改车友通讯录
     *
     * @param myCarBook 车友通讯录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMyCarBook(MyCarBook myCarBook) {
        String autoCheck = myCarBook.getAutoCheck();
        if (StringUtils.isNotEmpty(autoCheck) && autoCheck.equals("1")){

        }else {
            myCarBook.setAutoCheck("0");
        }
        Integer id = myCarBook.getId();
        Integer userId = myCarBook.getUserId();
        if (Objects.isNull(userId)) {
            throw new CustomException("关联用户不能为空", 400);
        }
        //
        //WxUser wxUser = wxUserService.selectWxUserById(userId);
        String subCard = myCarBook.getSubCard();
        String car = myCarBook.getCar();
        if (StringUtils.isNotEmpty(subCard)) {
            StringBuilder ran = new StringBuilder(subCard);
            while (ran.length() < 4) {
                ran.insert(0, "0");
            }
            subCard = ran.toString();
        }
        //肯定有值
        //MyCarBook myCarBook1 = selectMyCarBookById(id);
        //Boolean flag =false;
        //修改副牌
        if (StringUtils.isNotEmpty(subCard)){
            MyCyhMark myCyhMark = myCyhMarkService.selectMyCyhMarkByNumAndCar(subCard,car);
            if (myCyhMark == null){
                List<MyCyhMark> myCyhMarkList = myCyhMarkService.selectMyCyhMarkByNum(subCard);
                if (myCyhMarkList.size()>0){
                    for (MyCyhMark cyhMark : myCyhMarkList) {
                        if (cyhMark.getUserId().equals(userId)){
                            cyhMark.setNumber(subCard);
                            cyhMark.setCarId(car);
                            myCyhMarkService.updateMyCyhMark(cyhMark);
                        }
                    }

                }else {
                    //新增
                    MyCyhMark  myCyhMark2= new MyCyhMark();
                    myCyhMark2.setUserId(userId);
                    myCyhMark2.setNumber(subCard);
                    myCyhMark2.setNatime(new Date());
                    myCyhMark2.setCarId(car);
                    myCyhMarkService.insertMyCyhMark(myCyhMark2);
                }

            }else {
                if (myCyhMark.getUserId().equals(userId)){
                    myCyhMark.setCarId(car);
                    myCyhMarkService.updateMyCyhMark(myCyhMark);

                } else {
                    throw new CustomException("该副牌和车型已经被其他用户认证", 400);
                }
            }

            /*MyCarBook myCarBook2 = myCarBookMapper.selectByFupaiAndUserId(subCard,userId);
            if (myCarBook2 != null) {
                if (!myCarBook2.getId().equals(id)){
                }

            }*/
        }

        //修改副牌
        /*if (StringUtils.isNotEmpty(subCard)) {

            MyCarBook myCarBook2 = myCarBookMapper.selectByFupai(subCard);
            if (myCarBook2 != null) {
                String subCard1 = myCarBook1.getSubCard();
                if (subCard.equals(subCard1)) {
                    if (!id.equals(myCarBook2.getId())) {
                        throw new CustomException("该副牌已经被其他用户认证", 400);
                    }
                    //没有修改副牌

                } else {
                    //修改
                    MyCyhMark myCyhMark = myCyhMarkService.selectMyCyhMarkByNum(myCarBook1.getSubCard());
                    if (myCyhMark != null) {
                        if (myCyhMark.getUserId().equals(userId)){
                            //同一个人就修改
                            myCyhMark.setNumber(subCard);
                            myCyhMarkService.updateMyCyhMark(myCyhMark);
                        }else {
                            throw new CustomException("该副牌已经被其他车主购买",400);
                        }

                    }else {
                        //新增
                        myCyhMark= new MyCyhMark();
                        myCyhMark.setUserId(userId);
                        myCyhMark.setNumber(subCard);
                        myCyhMark.setNatime(new Date());
                        myCyhMarkService.insertMyCyhMark(myCyhMark);
                    }

                }

            }else {
                MyCyhMark myCyhMark = myCyhMarkService.selectMyCyhMarkByNum(myCarBook1.getSubCard());
                if (myCyhMark != null) {
                    if (myCyhMark.getUserId().equals(userId)){
                        //同一个人就修改
                        myCyhMark.setNumber(subCard);
                        myCyhMarkService.updateMyCyhMark(myCyhMark);
                    }else {
                        throw new CustomException("该副牌已经被其他车主购买",400);
                    }

                }else {
                    //新增
                    myCyhMark= new MyCyhMark();
                    myCyhMark.setUserId(userId);
                    myCyhMark.setNumber(subCard);
                    myCyhMark.setNatime(new Date());
                    myCyhMarkService.insertMyCyhMark(myCyhMark);
                }
            }

        }*/

        myCarBook.setSubCard(subCard);
        return myCarBookMapper.updateMyCarBook(myCarBook);
    }

    /**
     * 批量删除车友通讯录
     *
     * @param ids 需要删除的车友通讯录ID
     * @return 结果
     */
    @Override
    public int deleteMyCarBookByIds(Integer[] ids) {
        return myCarBookMapper.deleteMyCarBookByIds(ids);
    }

    /**
     * 删除车友通讯录信息
     *
     * @param id 车友通讯录ID
     * @return 结果
     */
    @Override
    public int deleteMyCarBookById(Integer id) {
        return myCarBookMapper.deleteMyCarBookById(id);
    }

    @Override
    public MyCarBook selectMyCarBookByUserId(Integer mid) {
        return myCarBookMapper.selectMyCarBookByUserId(mid);
    }

    @Transactional
    @Override
    public synchronized int insertMyCarBookWeb(MyCarBook myCarBook) {

        log.error("请求的参数1:{}", myCarBook);
        WxUser wxUser = SecurityUtils.getLoginUser().getWxUser();
        MyCarBook myCarBook1 = selectMyCarBookByUserId(wxUser.getMid());
        if (myCarBook1 != null) {
            return 0;
        }
        //门
        String verificationType = myCarBook.getVerificationType();
        if (StringUtils.isEmpty(verificationType)) {
            throw new CustomException("验证方式不能为空", 400);
        }
        if (!verificationType.equals("1") && !verificationType.equals("2") && !verificationType.equals("3") && !verificationType.equals("4")) {
            throw new CustomException("验证方式不符", 400);
        }
        if (verificationType.equals("1")) {
            myCarBook.setAutoCheck("1");
        } else {
            myCarBook.setAutoCheck("0");
        }
        myCarBook.setUserId(wxUser.getMid());
        myCarBook.setHeadImg(wxUser.getAvatar());
        //车辆信息
        CarInfo carInfo = myCarBook.getCarInfo();
        if (carInfo == null) {
            throw new CustomException("行驶证信息不能为空", 400);
        }
        //身份证
        IdCard idcard = myCarBook.getCardInfo();
        if (idcard == null) {
            throw new CustomException("身份证信息不能为空", 400);
        }

        if (verificationType.equals("1")) {
            if (!idcard.getName().equals(carInfo.getAll())) {
                throw new CustomException("身份证和驾驶证不符", 400);
            }
            myCarBook.setIsAuth("1");
        } else {
            myCarBook.setIsAuth("0");
        }
        //date_issue=20201123
        Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS2, carInfo.getDate_issue());//发证日期
        myCarBook.setExpirationInsurance(date);//保险
        myCarBook.setRealName(idcard.getName());
        myCarBook.setGender(idcard.getGender());
        myCarBook.setBirthday(idcard.getBirthday());
        myCarBook.setFrom(idcard.getFrom());
        myCarBook.setAge(idcard.getAge());
        myCarBook.setIdCard(idcard.getImg());
        myCarBookMapper.insertMyCarBook(myCarBook);

        MyCyhCar myCyhCar1 = myCyhCarService.selectByName(carInfo.getPlate_number());
        if (myCyhCar1 != null) {
            throw new CustomException("已经添加了该车辆", 400);
        }

        MyCyhCar myCyhCar = new MyCyhCar();
        myCyhCar.setName(carInfo.getPlate_number());
        myCyhCar.setProduct(carInfo.getBrand_model());
        myCyhCar.setPhoto(/*myCarBook.getDrivingPermit()*/ carInfo.getImg());
        myCyhCar.setUserId(wxUser.getMid());
        myCyhCarService.insertMyCyhCar(myCyhCar);

        MyCarCoupon myCarCoupon = new MyCarCoupon();
        myCarCoupon.setTitle("车友会洗车券");
        myCarCoupon.setCheckTime(new Date());
        myCarCoupon.setIsCheck(0);
        myCarCoupon.setUserId(wxUser.getMid());
        myCarCoupon.setNum(10);
        myCarCoupon.setExpireTime(DateUtils.addMonths(new Date(),6));//6个月
        myCarCouponService.insertMyCarCoupon(myCarCoupon);

        return 1;
    }

    @Transactional
    @Override
    public void updateMyCarBookWeb(MyCarBook myCarBook) {
        log.error("传递的通讯录参数:{}", myCarBook);
        WxUser wxUser = SecurityUtils.getLoginUser().getWxUser();
        String isAuth = myCarBook.getIsAuth();
        if (StringUtils.isEmpty(isAuth) || StringUtils.equals(isAuth, "0")) {
            String verificationType = myCarBook.getVerificationType();
            if (StringUtils.isEmpty(verificationType)) {
                throw new CustomException("验证方式不能为空", 400);
            }
            if (!verificationType.equals("1") && !verificationType.equals("2") && !verificationType.equals("3") && !verificationType.equals("4")) {
                throw new CustomException("验证方式不符", 400);
            }
            if (verificationType.equals("1")) {
                myCarBook.setAutoCheck("1");
            } else {
                myCarBook.setAutoCheck("0");
            }
            myCarBook.setUserId(wxUser.getMid());
            myCarBook.setHeadImg(wxUser.getAvatar());
            //车辆信息
            CarInfo carInfo = myCarBook.getCarInfo();
            if (carInfo == null) {
                throw new CustomException("行驶证信息不能为空", 400);
            }
            myCarBook.setAutoCheck("1");
            //身份证
            /*IdCard idcard = myCarBook.getCardInfo();
            if (idcard == null) {
                throw new CustomException("身份证信息不能为空", 400);
            }*/

            /*if (verificationType.equals("1")) {
                if (!idcard.getName().equals(carInfo.getAll())) {
                    throw new CustomException("身份证和驾驶证不符", 400);
                }
                myCarBook.setIsAuth("1");
            } else {
                *//*if (StringUtils.isNotEmpty(myCarBook.getAutoCheck()) && myCarBook.getAutoCheck().equals("1")  ){
                    myCarBook.setIsAuth("1");

                }else {

                    myCarBook.setIsAuth("0");
                }*//*
                myCarBook.setIsAuth("0");

            }*/

            myCarBook.setRealName(carInfo.getAll());
            //myCarBook.setGender(idcard.getGender());
            //myCarBook.setBirthday(idcard.getBirthday());
            //myCarBook.setFrom(idcard.getFrom());
            //myCarBook.setAge(idcard.getAge());
            //myCarBook.setCarType(carInfo.getBrand_model());
            myCarBookMapper.updateMyCarBook(myCarBook);

            MyCyhCar myCyhCar1 = myCyhCarService.selectByName(carInfo.getPlate_number());
            if (myCyhCar1 != null) {
                throw new CustomException("已经添加了该车辆", 400);
            }

            MyCyhCar myCyhCar = new MyCyhCar();
            myCyhCar.setName(carInfo.getPlate_number());
            myCyhCar.setProduct(carInfo.getBrand_model());
            myCyhCar.setPhoto(carInfo.getImg());
            myCyhCar.setUserId(wxUser.getMid());
            myCyhCarService.insertMyCyhCar(myCyhCar);

            /*MyCarCoupon myCarCoupon = new MyCarCoupon();
            myCarCoupon.setTitle("车友汇洗车券");
            myCarCoupon.setDesc("会员认证赠送洗车券");
            myCarCoupon.setCheckTime(new Date());
            myCarCoupon.setIsCheck(0);
            myCarCoupon.setUserId(wxUser.getMid());
            myCarCoupon.setNum(10);
            myCarCoupon.setExpireTime(DateUtils.addMonths(new Date(),6));//6个月
            myCarCouponService.insertMyCarCoupon(myCarCoupon);*/
        } else {
            myCarBookMapper.updateMyCarBook(myCarBook);
        }

    }

    @Override
    public Object getInfo(String data, Integer type) {

        Map<String, String> access_token = redisCache.getCacheObject("access_token");
        if (access_token == null) {
            access_token = Sample.getToken();
            String expires_in = String.valueOf(access_token.get("expires_in"));
            //System.out.println("expires_in:"+expires_in);
            redisCache.setCacheObject("access_token", access_token, Integer.valueOf(expires_in), TimeUnit.SECONDS);

        } else {
            String expires_in = String.valueOf(access_token.get("expires_in"));
            if (Integer.valueOf(expires_in) < 3600) {
                access_token = Sample.getToken();
                redisCache.setCacheObject("access_token", access_token, Integer.valueOf(expires_in), TimeUnit.SECONDS);
            }
        }
        ////上传照片 1行驶证 2 车辆照片 3 身份证 4 结婚证 5 营业执照 6 户口本
        if (type.equals(1)) {
            //身份证
            IdCard idcard = Sample.idcard(data);
            if (idcard == null || StringUtils.isEmpty(idcard.getName())) {
                throw new CustomException("身份证识别有误", 400);
            }
            idcard.setImg(data);
            return idcard;
        } else if (type.equals(2)) {
            //驾驶证
            CarInfo carInfo = Sample.vehicleLicense(data);
            //System.out.println(carInfo);
            if (carInfo == null) {
                throw new CustomException("行驶证识别有误", 400);
            }
            carInfo.setImg(data);
            return carInfo;

        }else if (type.equals(3)){
            //结婚证
            PersonInfo personInfo = Sample.marriageCertificate(data);
            if (personInfo == null) {
                throw new CustomException("结婚证识别有误", 400);
            }
            personInfo.setImg(data);
            return personInfo;

        }else if (type.equals(4)){
            //营业执照
            BusinessLicense businessLicense = Sample.test1(data);
            if (businessLicense == null) {
                throw new CustomException("营业执照识别有误", 400);
            }
            businessLicense.setImg(data);
            return businessLicense;
        }
        return null;
    }

    @Transactional
    @Override
    public synchronized int insertMyCarBookWeb1(MyCarBook myCarBook) {

        log.error("请求的参数1:{}", myCarBook);
        WxUser wxUser = SecurityUtils.getLoginUser().getWxUser();
        MyCarBook myCarBook1 = selectMyCarBookByUserId(wxUser.getMid());
        if (myCarBook1 != null) {
            return 0;
        }

        String verificationType = myCarBook.getVerificationType();
        /*if (StringUtils.isEmpty(verificationType)) {
            throw new CustomException("验证方式不能为空", 400);
        }*/
        /*if (!verificationType.equals("1") && !verificationType.equals("2") && !verificationType.equals("3") && !verificationType.equals("4")) {
            throw new CustomException("验证方式不符", 400);
        }*/

        /*if (verificationType.equals("1")) {
            myCarBook.setAutoCheck("1");
        } else {
            myCarBook.setAutoCheck("0");
        }*/

        myCarBook.setUserId(wxUser.getMid());
        myCarBook.setHeadImg(wxUser.getAvatar());
        //车辆信息
        CarInfo carInfo = myCarBook.getCarInfo();
        if (carInfo == null) {
            throw new CustomException("行驶证信息不能为空", 400);
        }
        myCarBook.setAutoCheck("1");
        //身份证
        /*IdCard idcard = myCarBook.getCardInfo();
        if (idcard == null) {
            throw new CustomException("身份证信息不能为空", 400);
        }*/

        /*if (verificationType.equals("1")) {
            if (!idcard.getName().equals(carInfo.getAll())) {
                throw new CustomException("身份证和驾驶证不符", 400);
            }
            myCarBook.setIsAuth("1");
        } else {
            *//*if (StringUtils.isNotEmpty(myCarBook.getAutoCheck()) && myCarBook.getAutoCheck().equals("1")  ){
                myCarBook.setIsAuth("1");

            }else {

                myCarBook.setIsAuth("0");
            }*//*
            myCarBook.setIsAuth("0");
        }*/
        //date_issue=20201123
        if (StringUtils.isNotEmpty(carInfo.getDate_issue())){

            try {
                Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS2, carInfo.getDate_issue());//发证日期
                myCarBook.setExpirationInsurance(date);//保险
            }catch (Exception e){
                throw new CustomException("证件打码了或者证件照片不清晰", 400);
            }
        }else {
            throw new CustomException("证件打码了或者证件照片不清晰", 400);
        }
        myCarBook.setRealName(carInfo.getAll());
        myCarBook.setIsAuth("1");
        //myCarBook.setGender(idcard.getGender());
        //myCarBook.setBirthday(idcard.getBirthday());
        //myCarBook.setFrom(idcard.getFrom());
        //myCarBook.setAge(idcard.getAge());
        //myCarBook.setIdCard(idcard.getImg());
        myCarBookMapper.insertMyCarBook(myCarBook);

        MyCyhCar myCyhCar1 = myCyhCarService.selectByName(carInfo.getPlate_number());
        if (myCyhCar1 != null) {
            throw new CustomException("已经添加了该车辆", 400);
        }

        MyCyhCar myCyhCar = new MyCyhCar();
        myCyhCar.setName(carInfo.getPlate_number());
        myCyhCar.setProduct(carInfo.getBrand_model());
        myCyhCar.setPhoto(/*myCarBook.getDrivingPermit()*/ carInfo.getImg());
        myCyhCar.setUserId(wxUser.getMid());
        myCyhCarService.insertMyCyhCar(myCyhCar);

        /*WxUser wxUser1 = wxUserService.selectWxUserById(wxUser.getMid());
        wxUser1.setIsAuth(myCarBook.getIsAuth());
        wxUserService.updateWxUser(wxUser1);*/
        return 1;


    }

    @Override
    public List<MyCarBook> selectMyCarBookListWeb(MyCarBook myCarBook) {
        return myCarBookMapper.selectMyCarBookListWeb(myCarBook);
    }
}
